#!/usr/bin/python
# coding=UTF-8
# noinspection PySingleQuotedDocstring
"""CopyRight © 2020 Luomuyu.All Rights Reserved."""
"""Version:v1.1.0"""
import requests
import time
import json
import os
import re
import urllib.request
import hashlib
import platform
config = os.path.isfile("config.ini")
if config == True:
    confp = open("config.ini","r",encoding="utf-8")
    config = confp.read()
    if "[CQinfo]" in config:
        qq_u = re.findall("qq_url=(?:(?:[0,1]?\d?\d|2[0-4]\d|25[0-5])\.){3}(?:[0,1]?\d?\d|2[0-4]\d|25[0-5]):\d{0,5}",config,re.S)[0]
        qq_url = re.findall("(?:(?:[0,1]?\d?\d|2[0-4]\d|25[0-5])\.){3}(?:[0,1]?\d?\d|2[0-4]\d|25[0-5]):\d{0,5}",qq_u,re.S)[0]
        group_i = re.findall("group_id=[1-9][0-9]{5,}",config,re.S)[0]
        group_id = re.findall("[1-9][0-9]{5,}",group_i,re.S)[0]
        livei = re.findall("liveid=[1-9][0-9]*",config,re.S)[0]
        liveid = re.findall("[1-9][0-9]*",livei,re.S)[0]
        rec = re.findall("record=[aeflrstu]{4,5}",config,re.S)[0]
        record = re.findall("[aeflrstu]{4,5}",rec,re.S)[0]
        ff = re.findall("ffmpeg=[aeflrstu]{4,5}",config,re.S)[0]
        ffmpeg = re.findall("[aeflrstu]{4,5}",ff,re.S)[0]
        confp.close()
    else:
        os.remove("config.ini")
        print("配置文件损坏，请重新输入相关信息...")
        confp = open("config.ini","w",encoding="utf-8")
        qq_url = input("请输入HTTP监听服务器“IP:端口”：")
        group_id = input("请输入通知群群号：")
        liveid = input("请输入直播间ID：")
        rec = input("是否对直播内容进行录制？(y/n)")
        if rec == "y":
            record = "true"
            ff = input("录制完成后是否需要无损转码为mp4？(y/n)")
            if ff == "y":
                ffmpeg = "true"
            else:
                ffmpeg = "false"
        else:
            record = "false"
            ffmpeg = "false"
        print("[CQinfo]"+"\nqq_url="+qq_url+"\ngroup_id="+group_id+"\n\n\n[LIVEinfo]\nliveid="+liveid+"\n\n\n[RECinfo]\nrecord="+record+"\nffmpeg="+ffmpeg,file=confp)
        confp.close()
else:
    print("检测到第一次启动，正在释放文件...")
    confp = open("config.ini","w",encoding="utf-8")
    qq_url = input("请输入HTTP监听服务器“IP:端口”：")
    group_id = input("请输入通知群群号：")
    liveid = input("请输入直播间ID：")
    rec = input("是否对直播内容进行录制？(y/n)")
    if rec == "y":
        record = "true"
        ff = input("录制完成后是否需要无损转码为mp4？(y/n)")
        if ff == "y":
            ffmpeg = "true"
        else:
            ffmpeg = "false"
    else:
        record = "false"
        ffmpeg = "false"
    print("[CQinfo]"+"\nqq_url="+qq_url+"\ngroup_id="+group_id+"\n\n\n[LIVEinfo]\nliveid="+liveid+"\n\n\n[RECinfo]\nrecord="+record+"\nffmpeg="+ffmpeg,file=confp)
    confp.close()
if platform.system()=="Windows":
    ffmpegname = "ffmpeg.exe"
if platform.system()=="Linux":
    ffmpegname = "./ffmpeg"
liveurl = "https://api.live.bilibili.com/room/v1/Room/room_init?id="+liveid
headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36"}
print("开始监测直播间:"+liveid)
code_list = [200,301,302,401]
poststatus = "0"
number = "0"
while True:
    result = requests.get(url=liveurl,headers=headers)
    liveobj = json.loads(result.text)
    livestatus = liveobj["data"]["live_status"]
    if poststatus == 1:
        flvurl = "https://api.live.bilibili.com/room/v1/Room/playUrl?cid="+liveid+"&platform=web&otype=json&quality=4"
        urljson = requests.get(url=flvurl,headers=headers)
        urlobj = json.loads(urljson.text)
        besturl = urlobj["data"]["durl"][0]["url"]
        if livestatus == 1:
            if record == "true":
                statuscode = requests.head(url=besturl,headers=headers).status_code
                if statuscode in code_list:
                    print("重新尝试录制...")
                    opener = urllib.request.build_opener()
                    opener.addheaders = [("user-agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36")]
                    urllib.request.install_opener(opener)
                    filename = "录制-"+liveid+"-"+time.strftime("%Y%m%d%H%M%S",time.localtime())+"-"+title
                    urllib.request.urlretrieve(besturl,os.path.join(filename+".flv"))
                    if ffmpeg == "true":
                        print("修复时间轴中...")
                        os.system(ffmpegname+" -i "+filename+".flv -vcodec copy -acodec copy "+filename+".mp4")
                        print("录制中断或直播结束")
                else:
                    uid = liveobj["data"]["uid"]
                    usrurl = "http://api.bilibili.com/x/space/acc/info?mid="+str(uid)
                    usr = requests.get(url=usrurl,headers=headers)
                    usrobj = json.loads(usr.text)
                    name = usrobj["data"]["name"]
                    title = usrobj["data"]["live_room"]["title"]
                    url = usrobj["data"]["live_room"]["url"]
                    cover = usrobj["data"]["live_room"]["cover"]
                    if record == "true":
                        recstatus = "是"
                    else:
                        recstatus = "否"
                    downmessage = "【下播提醒】\n[CQ:image,cache=0,file="+cover+"]"+"\n【频道名称】"+name+"\n【直播标题】"+title+"\n【直播地址】"+url+"\n【录制状态】"+recstatus+"\n【推送时间】"+time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
                    cqurl = "http://"+qq_url+"/send_group_msg?group_id="+group_id+"&message="+downmessage
                    cq = requests.get(url=cqurl,headers=headers)
                    cqobj = json.loads(cq.text)
                    back = cqobj["status"]
                    if back == "ok":
                        print("下播提醒推送成功！时间："+time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
                    else:
                        print("下播提醒推送失败，请检查机器人相关设置！")
                    poststatus = eval("int(poststatus)-1")
                    number = eval("int(number)+1")
                    print("第"+str(number)+"次检测，时间："+time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
                    time.sleep(15)
            else:
                statuscode = requests.head(url=besturl,headers=headers).status_code
                if statuscode in code_list:
                    number = eval("int(number)+1")
                    print("第"+str(number)+"次检测，时间："+time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
                    time.sleep(300)
                else:
                    uid = liveobj["data"]["uid"]
                    usrurl = "http://api.bilibili.com/x/space/acc/info?mid="+str(uid)
                    usr = requests.get(url=usrurl,headers=headers)
                    usrobj = json.loads(usr.text)
                    name = usrobj["data"]["name"]
                    title = usrobj["data"]["live_room"]["title"]
                    url = usrobj["data"]["live_room"]["url"]
                    cover = usrobj["data"]["live_room"]["cover"]
                    if record == "true":
                        recstatus = "是"
                    else:
                        recstatus = "否"
                    downmessage = "【下播提醒】\n[CQ:image,cache=0,file="+cover+"]"+"\n【频道名称】"+name+"\n【直播标题】"+title+"\n【直播地址】"+url+"\n【录制状态】"+recstatus+"\n【推送时间】"+time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
                    cqurl = "http://"+qq_url+"/send_group_msg?group_id="+group_id+"&message="+downmessage
                    cq = requests.get(url=cqurl,headers=headers)
                    cqobj = json.loads(cq.text)
                    back = cqobj["status"]
                    if back == "ok":
                        print("下播提醒推送成功！时间："+time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
                    else:
                        print("下播提醒推送失败，请检查机器人相关设置！")
                    number = eval("int(number)+1")
                    print("第"+str(number)+"次检测，时间："+time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
                    time.sleep(15)
        else:
            uid = liveobj["data"]["uid"]
            usrurl = "http://api.bilibili.com/x/space/acc/info?mid="+str(uid)
            usr = requests.get(url=usrurl,headers=headers)
            usrobj = json.loads(usr.text)
            name = usrobj["data"]["name"]
            title = usrobj["data"]["live_room"]["title"]
            url = usrobj["data"]["live_room"]["url"]
            cover = usrobj["data"]["live_room"]["cover"]
            if record == "true":
                recstatus = "是"
            else:
                recstatus = "否"
            downmessage = "【下播提醒】\n[CQ:image,cache=0,file="+cover+"]"+"\n【频道名称】"+name+"\n【直播标题】"+title+"\n【直播地址】"+url+"\n【录制状态】"+recstatus+"\n【推送时间】"+time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
            cqurl = "http://"+qq_url+"/send_group_msg?group_id="+group_id+"&message="+downmessage
            cq = requests.get(url=cqurl,headers=headers)
            cqobj = json.loads(cq.text)
            back = cqobj["status"]
            if back == "ok":
                print("下播提醒推送成功！时间："+time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
            else:
                print("下播提醒推送失败，请检查机器人相关设置！")
            poststatus = eval("int(poststatus)-1")
            number = eval("int(number)+1")
            print("第"+str(number)+"次检测，时间："+time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
            time.sleep(15)
    else:
        if livestatus == 1:
            number = eval("int(number)+1")
            print("第"+str(number)+"次检测，正在直播，时间："+time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
            uid = liveobj["data"]["uid"]
            usrurl = "http://api.bilibili.com/x/space/acc/info?mid="+str(uid)
            usr = requests.get(url=usrurl,headers=headers)
            usrobj = json.loads(usr.text)
            name = usrobj["data"]["name"]
            title = usrobj["data"]["live_room"]["title"]
            url = usrobj["data"]["live_room"]["url"]
            cover = usrobj["data"]["live_room"]["cover"]
            if record == "true":
                recstatus = "是"
            else:
                recstatus = "否"
            upmessage = "【直播提醒】\n[CQ:image,cache=0,file="+cover+"]"+"\n【频道名称】"+name+"\n【直播标题】"+title+"\n【直播地址】"+url+"\n【录制状态】"+recstatus+"\n【推送时间】"+time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
            cqurl = "http://"+qq_url+"/send_group_msg?group_id="+group_id+"&message="+upmessage
            cq = requests.get(url=cqurl,headers=headers)
            cqobj = json.loads(cq.text)
            back = cqobj["status"]
            if back == "ok":
                print("直播提醒推送成功！时间："+time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
            else:
                print("直播提醒推送失败，请检查机器人相关设置！")
            poststatus = eval("int(poststatus)+1")
            if record == "true":
                flvurl = "https://api.live.bilibili.com/room/v1/Room/playUrl?cid="+liveid+"&platform=web&otype=json&quality=4"
                urljson = requests.get(url=flvurl,headers=headers)
                urlobj = json.loads(urljson.text)
                besturl = urlobj["data"]["durl"][0]["url"]
                print("开始尝试录制...")
                opener = urllib.request.build_opener()
                opener.addheaders = [("user-agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36")]
                urllib.request.install_opener(opener)
                filename = "录制-"+liveid+"-"+time.strftime("%Y%m%d%H%M%S",time.localtime())+"-"+title
                urllib.request.urlretrieve(besturl,os.path.join(filename+".flv"))
                if ffmpeg == "true":
                    print("修复时间轴中...")
                    os.system(ffmpegname+" -i "+filename+".flv -vcodec copy -acodec copy "+filename+".mp4")
                print("录制中断或直播结束")
            else:
                time.sleep(300)
        else:
            number = eval("int(number)+1")
            print("第"+str(number)+"次检测，时间："+time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
            time.sleep(15)
